#!/usr/bin/env python3
"""
添加DeepSeek配置到系统配置表的脚本
"""
import os
import sys
import sqlite3
import argparse

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
root_dir = os.path.dirname(parent_dir)
sys.path.insert(0, parent_dir)

def add_deepseek_config(db_path, api_key=None):
    """添加DeepSeek配置到系统配置表"""
    if not os.path.exists(db_path):
        print(f"错误: 数据库文件不存在: {db_path}")
        return False
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查system_config表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='system_config'")
        if not cursor.fetchone():
            print("创建system_config表...")
            cursor.execute("""
            CREATE TABLE system_config (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                key VARCHAR(100) NOT NULL UNIQUE,
                value TEXT,
                description TEXT,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
            """)
            conn.commit()
        
        # 添加配置项
        config_items = [
            ('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions', 'DeepSeek API URL'),
            ('DEEPSEEK_MODEL', 'deepseek-chat', 'DeepSeek 模型名称'),
            ('DEEPSEEK_TEMPERATURE', '0.1', 'DeepSeek 模型温度'),
            ('DEEPSEEK_MAX_TOKENS', '4000', 'DeepSeek 最大令牌数')
        ]
        
        # 如果提供了API密钥，也添加到配置中
        if api_key:
            config_items.append(('DEEPSEEK_API_KEY', api_key, 'DeepSeek API密钥'))
        
        for key, value, description in config_items:
            # 检查配置是否已存在
            cursor.execute("SELECT id FROM system_config WHERE key = ?", (key,))
            if cursor.fetchone():
                # 更新现有配置
                cursor.execute(
                    "UPDATE system_config SET value = ?, description = ? WHERE key = ?",
                    (value, description, key)
                )
                print(f"更新配置: {key}")
            else:
                # 添加新配置
                cursor.execute(
                    "INSERT INTO system_config (key, value, description) VALUES (?, ?, ?)",
                    (key, value, description)
                )
                print(f"添加新配置: {key}")
        
        conn.commit()
        
        # 验证配置是否添加成功
        cursor.execute("SELECT key, value FROM system_config WHERE key LIKE 'DEEPSEEK_%'")
        configs = cursor.fetchall()
        print("\n已添加或更新的DeepSeek配置:")
        for key, value in configs:
            # 如果是API密钥，隐藏部分内容
            if key == 'DEEPSEEK_API_KEY' and value:
                masked_value = value[:4] + '*' * (len(value) - 8) + value[-4:] if len(value) > 8 else '****'
                print(f"  {key}: {masked_value}")
            else:
                print(f"  {key}: {value}")
        
        conn.close()
        return True
    
    except Exception as e:
        print(f"错误: {str(e)}")
        return False

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='添加DeepSeek配置到系统配置表')
    parser.add_argument('--db', default=os.path.join(parent_dir, 'twrpa.db'), help='数据库文件路径')
    parser.add_argument('--api-key', help='DeepSeek API密钥')
    
    args = parser.parse_args()
    
    # 如果未提供API密钥，尝试从环境变量获取
    api_key = args.api_key or os.environ.get('DEEPSEEK_API_KEY')
    
    if not api_key:
        print("警告: 未提供API密钥。您可以稍后在系统配置界面中添加。")
    
    result = add_deepseek_config(args.db, api_key)
    
    if result:
        print("\nDeepSeek配置已成功添加或更新。")
        print("您可以通过系统配置界面查看或修改这些配置。")
    else:
        print("\n添加DeepSeek配置失败。")
        sys.exit(1) 